package org.example.config.sequence.configs.beans;

import org.example.config.sequence.configs.SpringConfigAutoConfig;
import org.example.config.sequence.inspect.Inspector;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * 通过{@link Component @Component},{@link Bean @Bean}等注解声明方式加载，也可通过注册{@link BeanDefinition}方式加载
 * <p>
 * 本示例中通过{@link Component @Component}声明方式加载，如果已经在{@link SpringConfigAutoConfig}中通过{@link Bean @Bean}方式声明，则会抛出异常: The bean 'myBeanPostProcessorBean', defined in class path resource [org/example/config/configs/SpringConfigAutoConfig.class], could not be registered.
 */
@Component
public class MyBeanPostProcessorBean implements InitializingBean, DisposableBean, BeanNameAware, SmartLifecycle {
    @Value("${config.property1}")
    private String property1;
    private String beanName;

    public MyBeanPostProcessorBean() {
        Inspector.constructor(MyBeanPostProcessorBean.class);
    }

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }

    public String getProperty1() {
        return property1;
    }

    public void setProperty1(String property1) {
        Inspector.log(MyBeanPostProcessorBean.class, beanName + " setProperty1 from {" + this.property1 + "} to {" + property1 + "}");
        this.property1 = property1;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Inspector.log(MyBeanPostProcessorBean.class, beanName + " afterPropertiesSet");
        Inspector.log(MyBeanPostProcessorBean.class, beanName + " prop1 is {" + property1 + "}");
    }

    @Override
    public void destroy() throws Exception {
        Inspector.log(MyBeanPostProcessorBean.class, beanName + " destroy");
    }

    @Override
    public void start() {
        Inspector.log(MyBeanPostProcessorBean.class, beanName + " start");
    }

    @Override
    public void stop() {
        Inspector.log(MyBeanPostProcessorBean.class, beanName + " stop");
    }

    @Override
    public boolean isRunning() {
        Inspector.log(MyBeanPostProcessorBean.class, beanName + " isRunning");
        return false;
    }
}
